<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import type { LoginForm, RegisterForm } from '@/stores/user'
import type { FormInstance, FormRules } from 'element-plus'

// ==================== Props & Emits ====================

interface Props {
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'login-success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// ==================== 状态 ====================

const userStore = useUserStore()

/** 当前Tab (login/register) */
const activeTab = ref<'login' | 'register'>('login')

/** 登录表单 */
const loginForm = reactive<LoginForm>({
  username: '',
  password: ''
})

/** 注册表单 */
const registerForm = reactive<RegisterForm>({
  username: '',
  password: '',
  confirmPassword: ''
})

/** 加载状态 */
const loading = ref(false)

/** 表单引用 */
const loginFormRef = ref<FormInstance>()
const registerFormRef = ref<FormInstance>()

// ==================== 表单验证规则 ====================

const loginRules: FormRules<LoginForm> = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

const registerRules: FormRules<RegisterForm> = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3-20个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (_rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次密码输入不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// ==================== 方法 ====================

/** 关闭对话框 */
const handleClose = () => {
  emit('update:modelValue', false)
  // 重置表单
  setTimeout(() => {
    loginFormRef.value?.resetFields()
    registerFormRef.value?.resetFields()
    activeTab.value = 'login'
  }, 300)
}

/** 处理登录 */
const handleLogin = async () => {
  if (!loginFormRef.value) return

  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const result = await userStore.login(loginForm)

        if (result.success) {
          ElMessage.success(result.message)
          emit('login-success')
          handleClose()
        } else {
          ElMessage.error(result.message)
        }
      } catch (error) {
        ElMessage.error('登录失败,请稍后重试')
        console.error('登录错误:', error)
      } finally {
        loading.value = false
      }
    }
  })
}

/** 处理注册 */
const handleRegister = async () => {
  if (!registerFormRef.value) return

  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const result = await userStore.register(registerForm)

        if (result.success) {
          ElMessage.success(result.message)
          // 注册成功后切换到登录Tab
          activeTab.value = 'login'
          // 自动填充用户名
          loginForm.username = registerForm.username
          loginForm.password = ''
        } else {
          ElMessage.error(result.message)
        }
      } catch (error) {
        ElMessage.error('注册失败,请稍后重试')
        console.error('注册错误:', error)
      } finally {
        loading.value = false
      }
    }
  })
}

/** 切换Tab时重置表单 */
const handleTabChange = () => {
  loginFormRef.value?.clearValidate()
  registerFormRef.value?.clearValidate()
}
</script>

<template>
  <el-dialog
    :model-value="props.modelValue"
    :show-close="true"
    :close-on-click-modal="false"
    width="450px"
    class="login-dialog"
    @close="handleClose"
  >
    <!-- 自定义Header -->
    <template #header>
      <div class="dialog-header">
        <div class="header-icon">🎓</div>
        <h2 class="header-title">欢迎来到智慧招考平台</h2>
        <p class="header-subtitle">登录享受更多服务</p>
      </div>
    </template>

    <!-- Tab切换 -->
    <el-tabs v-model="activeTab" class="auth-tabs" @tab-change="handleTabChange">
      <!-- 登录Tab -->
      <el-tab-pane label="登录" name="login">
        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          label-width="0"
          class="auth-form"
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              :prefix-icon="User"
              placeholder="请输入用户名"
              size="large"
              clearable
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              :prefix-icon="Lock"
              type="password"
              placeholder="请输入密码"
              size="large"
              show-password
              clearable
              @keyup.enter="handleLogin"
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              size="large"
              :loading="loading"
              class="submit-button"
              @click="handleLogin"
            >
              {{ loading ? '登录中...' : '登录' }}
            </el-button>
          </el-form-item>

          <!-- 提示信息 -->
          <div class="form-tip">
            <el-text type="info" size="small">
              💡 测试账号: admin / 123456 (或任意用户名密码)
            </el-text>
          </div>
        </el-form>
      </el-tab-pane>

      <!-- 注册Tab -->
      <el-tab-pane label="注册" name="register">
        <el-form
          ref="registerFormRef"
          :model="registerForm"
          :rules="registerRules"
          label-width="0"
          class="auth-form"
        >
          <el-form-item prop="username">
            <el-input
              v-model="registerForm.username"
              :prefix-icon="User"
              placeholder="请输入用户名 (3-20位)"
              size="large"
              clearable
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="registerForm.password"
              :prefix-icon="Lock"
              type="password"
              placeholder="请输入密码 (至少6位)"
              size="large"
              show-password
              clearable
            />
          </el-form-item>

          <el-form-item prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
              :prefix-icon="Lock"
              type="password"
              placeholder="请再次输入密码"
              size="large"
              show-password
              clearable
              @keyup.enter="handleRegister"
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              size="large"
              :loading="loading"
              class="submit-button"
              @click="handleRegister"
            >
              {{ loading ? '注册中...' : '注册' }}
            </el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<style scoped>
/* 对话框样式 */
.login-dialog :deep(.el-dialog) {
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 12px 48px rgba(79, 172, 254, 0.25);
}

.login-dialog :deep(.el-dialog__header) {
  padding: 0;
  margin: 0;
}

.login-dialog :deep(.el-dialog__body) {
  padding: 24px 32px 32px;
}

/* Header样式 */
.dialog-header {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  padding: 32px 32px 24px;
  text-align: center;
  position: relative;
  overflow: hidden;
}

.dialog-header::before {
  content: '✦';
  position: absolute;
  top: 20px;
  left: 30px;
  font-size: 24px;
  color: rgba(255, 215, 0, 0.6);
  animation: twinkle 3s ease-in-out infinite;
}

.dialog-header::after {
  content: '✦';
  position: absolute;
  bottom: 20px;
  right: 30px;
  font-size: 20px;
  color: rgba(255, 215, 0, 0.6);
  animation: twinkle 3s ease-in-out infinite 1.5s;
}

@keyframes twinkle {
  0%,
  100% {
    opacity: 0.3;
    transform: scale(1);
  }
  50% {
    opacity: 1;
    transform: scale(1.2);
  }
}

.header-icon {
  font-size: 48px;
  margin-bottom: 12px;
  filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.1));
  animation: float 3s ease-in-out infinite;
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-8px);
  }
}

.header-title {
  font-size: 24px;
  font-weight: 700;
  color: #ffffff;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-subtitle {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  margin: 0;
}

/* Tab样式 */
.auth-tabs :deep(.el-tabs__header) {
  margin-bottom: 24px;
}

.auth-tabs :deep(.el-tabs__nav-wrap::after) {
  display: none;
}

.auth-tabs :deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 600;
  color: #6c757d;
  transition: all 0.3s ease;
}

.auth-tabs :deep(.el-tabs__item:hover) {
  color: #4facfe;
}

.auth-tabs :deep(.el-tabs__item.is-active) {
  color: #4facfe;
}

.auth-tabs :deep(.el-tabs__active-bar) {
  background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
  height: 3px;
  border-radius: 2px;
}

/* 表单样式 */
.auth-form {
  margin-top: 8px;
}

.auth-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.auth-form :deep(.el-input__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(79, 172, 254, 0.08);
  transition: all 0.3s ease;
}

.auth-form :deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 12px rgba(79, 172, 254, 0.15);
}

.auth-form :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 4px 16px rgba(79, 172, 254, 0.25);
}

/* 提交按钮 */
.submit-button {
  width: 100%;
  height: 48px;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  border: none;
  box-shadow: 0 4px 16px rgba(79, 172, 254, 0.3);
  transition: all 0.3s ease;
}

.submit-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(79, 172, 254, 0.4);
}

.submit-button:active {
  transform: translateY(0);
}

/* 提示信息 */
.form-tip {
  margin-top: -8px;
  padding: 12px 16px;
  background: linear-gradient(135deg, #e8f5fe 0%, #f0f9ff 100%);
  border-radius: 10px;
  border-left: 3px solid #4facfe;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-dialog :deep(.el-dialog) {
    width: 90% !important;
    margin: 0 auto;
  }

  .login-dialog :deep(.el-dialog__body) {
    padding: 20px 24px 24px;
  }

  .dialog-header {
    padding: 24px 20px 20px;
  }

  .header-title {
    font-size: 20px;
  }

  .header-icon {
    font-size: 40px;
  }
}
</style>
